package com.matou.auth.controller;


import com.matou.auth.social.weixin.config.AuthWeChatConfig;
import com.matou.commons.constants.Resp;
import com.matou.commons.exception.CmAuthException;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.request.AuthWeChatOpenRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;

/**
 * @Author CM
 * @Date 2021/5/8 16:58
 * @Description AuthController
 * @Version 1.0
 */
@Slf4j
@RestController
public class AuthController {

    @Autowired
    private ConsumerTokenServices consumerTokenServices;

    @Autowired
    private AuthRequest wechatAuthRequest;

    @GetMapping("oauth/test")
    public String testOauth() {
        return "oauth";
    }

    @GetMapping("user")
    public Principal currentUser(Principal principal) {
        return principal;
    }

    @DeleteMapping("signout")
    public Resp signout(HttpServletRequest request) throws CmAuthException {
        String authorization = request.getHeader("Authorization");
        String token = StringUtils.replace(authorization, "bearer ", "");
        if (!consumerTokenServices.revokeToken(token)) {
            throw new CmAuthException("退出登录失败");
        }
        return Resp.success("退出登录成功");
    }

    @RequestMapping("/render")
    public void renderAuth(HttpServletResponse response) throws IOException {
        response.sendRedirect(wechatAuthRequest.authorize(AuthStateUtils.createState()));
    }

    @RequestMapping("/wechat/callback")
    public Object login(AuthCallback callback) {
        AuthRequest authRequest = wechatAuthRequest;
        return authRequest.login(callback);
    }

}
